package com.dmxh.shiro;

import cn.hutool.core.util.ObjectUtil;
import com.dmxh.pojo.TbUser;
import com.dmxh.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /*授权管理*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /*认证管理*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken passwordToken = (UsernamePasswordToken) authenticationToken;/*强转*/
        String username = passwordToken.getUsername();
        /*拿到用户名称  去查询  如果没有这个用户就提示去注册*/
        TbUser userResult = userService.queryUserByUsername(username);
        if (ObjectUtil.isEmpty(userResult)){
            return null;/*没有找到这个用户去注册*/
        }                                  //对象
        return new SimpleAuthenticationInfo(userResult, userResult.getPassword(), ByteSource.Util.bytes(userResult.getSalt()), "user");
    }
}
